const express = require('express');
const router = express.Router();
const util = require('../util/util')
const db = require('../database')


//登录路由
router.post('/login', (req, res) => {
  let username = req.body.username;
  //对密码进行加密验证
  // let password = util.encrypt(req.body.password);
  let password = req.body.password;
  // console.log('原密码', req.body.password, '现密码', password)
  console.log(username,password);
  //生成一个token
  // let token=util.encodeJwt();
  let sql = db.login(username, password);
  //生成以一个token
  let token = util.encodeJwt();
  console.log(sql)
  db.query(sql).then(data => {
    //在数据控能够查找到结果时，将token发送给前台
    console.log(token)
    if (data.length) {
      console.log('用户登录成功！');
      res.send({"code": "200", "message": "登录成功！","data":data, "token": token,});
    } else {
      res.send({"code": "401", "message": "账号或者密码错误，登录失败！"});
    }
  }, err => {
    res.send({"code": "401", "message": "账号或者密码错误，登录失败！"});
  })
});

// 注册
router.post('/register',(req, res) => {
  let username = req.body.username;
  let password = req.body.password;
  console.log(username,password);
  let sql = db.register(username, password);
  db.query(sql).then(data => {
    console.log(data)
    res.send({"code": "200", "message": "注册成功！"});
  },err => {
    res.send({"code": "401", "message": "服务器娘不小心走神了！稍后再试试吧！"});
  })
})


module.exports = router;